<?php

namespace app\admin\controller;

use app\admin\model\PohtoList as PohtoListModel;
use app\admin\model\PhotoBuy as PhotoBuyModel;
use app\admin\model\PohtoListImage as PohtoListImageModel;
use app\admin\model\PohtoReport as PohtoReportModel;
use app\admin\validate\CommonnValidate;
use app\admin\validate\PhotoValidate;
use app\admin\model\PohtoUser as PohtoUserModel;
use app\admin\model\Notice as NoticeModel;
use app\BaseController;
use GuzzleHttp\Client;
use think\facade\Db;

class PhotoList extends BaseController
{
    protected $middleware = [
        'Auth' => ['except' => ['zidong', 'userList']],
    ];

    public function zidong()
    {
        $client = new Client([
            'verify' => false
        ]);
        $page = $this->request->get('page');
        $result = $client->request('GET', 'https://coserlab.io/wp-json/wp/v2/posts?categories=1&per_page=10&page=' . $page);
        $result = json_decode($result->getBody()->getContents(), true);
        return result()->success($result);
    }

    public function list()
    {
        $params = $this->request->post(['current', 'size', 'type_id', 'id', 'name', 'country', 'author_id']);
        $validate = new CommonnValidate();
        if (!$validate->scene('list')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new PohtoListModel();
        $whereArr = [];
        if (isset($params['id']) && $params['id']) {
            $whereArr[] = ["id", "=", $params['id']];
        }
        if (isset($params['type_id']) && $params['type_id']) {
            $whereArr[] = ["type_id", "=", $params['type_id']];
        }
        if (isset($params['author_id']) && $params['author_id']) {
            $whereArr[] = ["author_id", "=", $params['author_id']];
        }
        if (isset($params['name']) && $params['name']) {
            $whereArr[] = ["name", "LIKE", '%' . $params['name'] . '%'];
        }
        if (isset($params['country']) && $params['country']) {
            $whereArr[] = ["country", "LIKE", '%' . $params['country'] . '%'];
        }
        $list = $sql
            ->where($whereArr)
            ->order('create_at desc')
            ->with(['tanName', 'userInfo'])
            ->withCount(['buy', 'report'])
            ->paginate([
                'list_rows' => request()->param('size'),
                'page' => request()->param('current'),
            ]);
        return result()->success($list);
    }

    public function detail()
    {
        $params = $this->request->post(['photo_id']);
        $sql = new PohtoListModel();
        $info = $sql->with(['tanName', 'userInfo'])->withCount(['buy', 'report'])->find($params['photo_id']);
        return result()->success($info);
    }

    public function buyList()
    {
        $params = $this->request->post(['current', 'size', 'photo_id', 'userid', 'name']);
        $sql = new PhotoBuyModel();
        $whereArr = [];
        $haswhereArr = [];
        if (isset($params['photo_id']) && $params['photo_id']) {
            $whereArr[] = ["photo_id", "=", $params['photo_id']];
        }
        if (isset($params['userid']) && $params['userid']) {
            $whereArr[] = ["userid", "=", $params['userid']];
        }
        $condition = isset($params['name']) && $params['name'];
        if ($condition) {
            $haswhereArr[] = ["name", "LIKE", '%' . $params['name'] . '%'];
        }
        $list = $sql
            ->where($whereArr)
            ->when($condition, function ($query) use ($haswhereArr) {
                $query->hasWhere('info', $haswhereArr);
            })
            ->order('create_at desc')
            ->with(['user', 'info'])
            ->paginate([
                'list_rows' => request()->param('size'),
                'page' => request()->param('current'),
            ]);
        return result()->success($list);
    }

    public function addEdit()
    {
        $params = $this->request->post(['id']);
        if (isset($params['id']) && $params['id']) {
            return $this->edit();
        }
        return $this->add();
    }

    public function add()
    {
        $params = $this->request->post(['type_id', 'book_type', 'name', 'country', 'private', 'author_id', 'tags', 'photo_count', 'video_count', 'netdisk', 'extracted_code', 'jiangkuaihe', 'zipSize', 'private', 'price', 'sort']);
        $validate = new PhotoValidate();
        if (!$validate->scene('listadd')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $params['releaseid'] = 3;
        $params['status'] = 'SUCCESS';
        $sql = new PohtoListModel();
        $info = $sql->where('name', $params['name'])->findOrEmpty();
        if (!$info->isEmpty()) {
            return result()->fail($info->id, 1);
        }
        $sql->save($params);
        return result()->success($sql->id);
    }

    public function edit()
    {
        $params = $this->request->post(['id', 'type_id', 'book_type', 'hot', 'selected', 'name', 'country', 'private', 'author_id', 'tags', 'photo_count', 'video_count', 'netdisk', 'extracted_code', 'jiangkuaihe', 'zipSize', 'price', 'sort']);
        $validate = new CommonnValidate();
        if (!$validate->scene('edit')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new PohtoListModel();
        $info = $sql->find($params['id']);
        $info->save($params);
        return result()->success("修改成功");
    }

    public function editprivate()
    {
        $params = $this->request->post(['id', 'private']);
        $validate = new CommonnValidate();
        if (!$validate->scene('edit')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new PohtoListModel();
        $info = $sql->find($params['id']);
        Db::startTrans();
        try {
            $info->save($params);
            if ($params['private'] === 1) {
                $reportSql = new PohtoReportModel();
                $list = $reportSql->where('photo_id', $params['id'])->where('status', 0)->select();
                $noticeArr = [];
                $noticeSql = new NoticeModel();
                foreach ($list as $key => $reportInfo) {
                    $noticeArr[] = [
                        "type" => "REPORT_SUCCESS",
                        "userId" => $reportInfo->user_id,
                        "content" => "举报成功,资源" . $info->name . "已从平台删除此资源,感谢您对平台的监督,我们会努力改进",
                        "association" => $reportInfo->photo_id
                    ];
                }
                $noticeSql->saveAll($noticeArr);
                $reportSql->where('photo_id', $params['id'])->where('status', 0)->update([
                    'status' => 1
                ]);
            }
            Db::commit();
            return result()->success("修改成功");
        } catch (\Throwable $th) {
            Db::rollback();
            return result()->fail($th->getMessage(), 500);
        }

    }

    public function pyAdd()
    {
        $params = $this->request->post(['type_id', 'name', 'author', 'institution_id']);
        $userSql = new PohtoUserModel();
        $user = $userSql->where('username', $params['author'])->findOrEmpty();
        if ($user->isEmpty()) {
            $userSql->save([
                'username' => $params['author'],
                'institution_id' => $params['institution_id'],
                'country' => '中国',
                'sort' => 1
            ]);
            $params['author_id'] = $userSql->getKey();
        } else {
            $params['author_id'] = $user['id'];
        }
        $params['country'] = '中国';
        $params['extracted_code'] = rand_number(4);
        $params['jiangkuaihe'] = 'xiaobaiquan';
        $params['private'] = false;
        $params['price'] = 50;
        $params['sort'] = 1;
        $sql = new PohtoListModel();
        $info = $sql->where('name', $params['name'])->findOrEmpty();
        if (!$info->isEmpty()) {
            return result()->success($info->id);
        }
        $sql->save($params);
        return result()->success($sql->id);
    }

    public function dels()
    {
        $params = $this->request->post(['ids']);
        $validate = new CommonnValidate();
        if (!$validate->scene('dels')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new PohtoListModel();
        $sql->destroy($params['ids']);
        $imgSql = new PohtoListImageModel();
        $list = $imgSql->where('photo_id', 'in', $params['ids'])->select();
        foreach ($list as $item) {
            $item->delete();
        }
        return result()->success("删除成功");
    }
}

